using System;
using System.Collections.Generic;
using LitJson;
using UnityEngine;
using UnityEngine.UI;

namespace CGF
{
    public class TabDevicesCtrl : MonoBehaviour
    {
        private TabDevices TabDevices;
        private List<JsonData> listData = new List<JsonData>();
        private List<JsonData> listShopData = new List<JsonData>();
        private int pageSize = 10, page, totalPage;

        void Awake()
        {
            TabDevices = new TabDevices();
            TabDevices.BindProperties(transform);

            TabDevices.BtnBatchRenew.gameObject.SetActive(false); //TODO
            TabDevices.BtnBatchRenew.SetClick(() =>
            {
                if (TabDevices.Empty.gameObject.activeSelf)
                {
                    Dialog.Alert(TabDevices.Empty.text);
                    return;
                }
                Dialog.Alert("Comming soon!");
            });
            TabDevices.BtnMore.SetClick(() =>
            {
                PanelLeaseDevices.Open();
            });
            TabDevices.BtnLease.SetClick(() =>
            {
                PanelLeaseDevices.Open();
            });

            TabDevices.ScrollView.gameObject.SetActive(true);
            TabDevices.Empty.gameObject.SetActive(false);
            TabDevices.Hot.gameObject.SetActive(false);
            TabDevices.ScrollViewShop.gameObject.SetActive(false);
            
            TabDevices.ScrollView.SetCellUpdateCallback((RectTransform cell, int index) =>
            {
                if (listData == null || index > listData.Count - 1)
                {
                    return;
                }
                JsonData data = listData[index];
                JsonData shopData = GlobalData.GetDeviceByShopId((int)data["shop_id"]);
                int type = (int)shopData["type"];
                string bgSprite = "";
                string sliderSprite = "";
                switch (type)
                {
                    case 1:
                        bgSprite = "pic_expbg";
                        sliderSprite = "pic_exptiao";
                        break;
                    case 2:
                        bgSprite = "pic_probg";
                        sliderSprite = "pic_protiao";
                        break;
                    case 3:
                        bgSprite = "pic_ultbg";
                        sliderSprite = "pic_ulttiao";
                        break;
                }
                cell.GetComponent<Image>().sprite = cell.Get<Sprite>(bgSprite);
                DateTime createTime = DateTime.Parse(data["created_at"].ToString());
                bool isPreparing = (DateTime.Now - createTime).TotalMinutes < Config.PreparingMinutes;
                bool isRunning = DateTime.Parse(data["expired_at"].ToString()) > DateTime.Now;
                cell.Get<Device>("Device").SetInfo(type, (int)shopData["period"], isRunning);
                cell.Get<Image>("Foregound").sprite = cell.Get<Sprite>(sliderSprite);
                string status = isRunning ? (isPreparing ? CommAssets.instance.I18N_preparing : CommAssets.instance.I18N_running) : CommAssets.instance.I18N_expired;
                cell.Get<Text>("TextState").text = status;
                cell.GetComponent<TabDevicesCtrlCell>().SetRunning(type, isRunning, isPreparing, createTime);
                cell.Get<FlashLight>("GreenLight").SetColor(isPreparing);
                cell.Get<GameObject>("GreenLight").SetActive(isRunning);
                cell.Get<CButton>("BtnDetail").text.text = CommAssets.instance.I18N_detail;
                cell.Get<Text>("TextTitle").text = Utils.GetI18N(shopData["name"].ToString());
                cell.Get<Text>("TextTitleSub").text = $"{TabDevices.I18N_code}:{data["id"]}";
                string taotalIncome = StringHelper.Format2Decimal((int)data["income"] * 0.01f);
                cell.Get<Text>("TodayIncome").text = $"{TabDevices.I18N_total_income}  <size=25><color=#CFA349>{I18N.Currency} {taotalIncome}</color></size>";
                int remainDays = GetRemainDays(data["expired_at"].ToString());
                cell.Get<Text>("TextRemain").text = $"{TabDevices.I18N_remain_day.Replace("{num}", remainDays.ToString())}";
                string id = data["id"].ToString();
                cell.Get<CButton>("BtnDetail").SetClick(() => { OpenDetail(id, taotalIncome); });
                CButton btnRenew = cell.Get<CButton>("BtnRenew");
                btnRenew.text.text = TabDevices.I18N_renew;
                btnRenew.SetClick(() =>
                {
                    PanelLeaseRenew.Open(data, shopData, remainDays, newExpiredAt =>
                    {
                        listData[index]["expired_at"] = newExpiredAt;
                        remainDays = GetRemainDays(listData[index]["expired_at"].ToString());
                        cell.Get<Text>("TextRemain").text = $"{TabDevices.I18N_remain_day.Replace("{num}", remainDays.ToString())}";
                    });
                });
                btnRenew.gameObject.SetActive(type > 1);
            });
            TabDevices.ScrollView.SetScrollToEndCallback(() =>
            {
                if (page < totalPage)
                {
                    page++;
                    ReqData(page);
                }
            });

            //热卖产品
            TabDevices.ScrollViewShop.SetCellUpdateCallback((RectTransform cell, int index) =>
            {
                JsonData data = listShopData[index];
                int type = Mathf.Max(1, (int)data["type"]);
                cell.Get<Device>("Device").SetInfo(type, (int)data["period"], false);
                string price = StringHelper.Format2Decimal((int)data["price"] * 0.01f);
                cell.Get<Text>("TextPrice").text = $"{I18N.Currency} {price}";
                cell.Get<Text>("TextTitle").text = Utils.GetI18N(data["name"].ToString());
                cell.Get<Text>("TextTitleSub").text = CommAssets.instance.I18N_pre_income + ":" + StringHelper.SurportSpace(Utils.GetI18N(data["subtitle"].ToString()).Replace("\\n", ""));
                CButton btnLease = cell.Get<CButton>("BtnLease");
                btnLease.text.text = TabDevices.I18N_lease_atonce;
                btnLease.SetClick(() =>
                {
                    PanelLeasePay.Open(data, ReloadDevices);
                });
            });
        }

        private async void OnEnable()
        {
            await GlobalData.LoadAllSellDevices();
            ReloadDevices();
        }

        private void Start()
        {
            TabDevices.TextCount.text = $"{TabDevices.I18N_total}：0";
        }

        public void ReloadDevices()
        {
            UserInfo.RefreshWallet();
            listData.Clear();
            page = 1;
            ReqData(page);
            TabDevices.ScrollView.ScrollToHead();
        }

        private async void ReqData(int page)
        {
            //读取我已有的设备
            var res = await Network.Get($"/v1/order/bot?limit={pageSize}&page={page}");
            totalPage = Mathf.CeilToInt((int)res.jsonData["data"]["totalCount"] / (float)pageSize);
            TabDevices.TextCount.text = $"{TabDevices.I18N_total}：{res.jsonData["data"]["totalCount"]}";
            JsonData list = res.jsonData["data"]["bot"];
            for (int i = 0; i < list.Count; i++)
            {
                listData.Add(list[i]);
                JsonData shopData = GlobalData.GetDeviceByShopId((int)list[i]["shop_id"]);
                if ((int)shopData["type"] == 1)
                {
                    UserInfo.HaveBoughtExpDevice = true;
                }
            }
            TabDevices.ScrollView.SetTotalNumber(listData.Count);
            TabDevices.Empty.gameObject.SetActive(listData.Count == 0);
            TabDevices.Hot.gameObject.SetActive(listData.Count == 0);
            TabDevices.ScrollViewShop.gameObject.SetActive(listData.Count == 0);

            //请求热卖商品
            if (TabDevices.ScrollViewShop.gameObject.activeSelf)
            {
                await GlobalData.LoadAllSellDevices();
                listShopData.Clear();
                for (int i = 0; i < GlobalData.allSellDevices.Count; i++)
                {
                    if (UserInfo.HaveBoughtExpDevice)
                    {
                        bool isExp = (int)GlobalData.allSellDevices[i]["type"] == 1;
                        if (isExp)
                        {
                            continue;
                        }
                    }
                    listShopData.Add(GlobalData.allSellDevices[i]);
                }
                TabDevices.ScrollViewShop.SetTotalNumber(listShopData.Count);
            }
        }

        private int GetRemainDays(string eventTimeString)
        {
            DateTime eventTime = DateTime.Parse(eventTimeString);
            DateTime currentTime = DateTime.Now;
            TimeSpan timeRemaining = eventTime - currentTime;
            if (timeRemaining.TotalSeconds > 0)
            {
                if (timeRemaining.TotalDays >= 1)
                {
                    return Mathf.CeilToInt((float)timeRemaining.TotalDays);
                }
            }
            return 0;
        }

        private void OpenDetail(string botId, string income)
        {
            PanelDeviceDetail.Open(botId, income);
        }
    }
}
